package com.yykj.hospital.server.aspcet;

import com.yykj.common.service.RedisService;
import com.yykj.common.util.GsonUtil;
import com.yykj.common.util.LocalRequestUtil;
import com.yykj.hospital.server.annotation.HospitalAdminLogAnnotation;
import com.yykj.hospital.server.dto.HospitalLoginInfo;
import com.yykj.hospital.server.model.entity.HospitalAdminLog;
import com.yykj.hospital.server.service.HospitalAdminLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * Created by chendg
 * on 2020/9/8 0008.
 */

@Order(10)
@Aspect
@Slf4j
@Component
public class HospitalAdminLogAspect {
    @Pointcut("@annotation(com.yykj.hospital.server.annotation.HospitalAdminLogAnnotation))")
    public void verify() {
    }

    @Before("verify()")
    public void doVerify(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        HospitalAdminLogAnnotation annotation = method.getAnnotation(HospitalAdminLogAnnotation.class);

        String token = LocalRequestUtil.getToken();
        String tokenValue = redisService.get(token);
        HospitalLoginInfo loginInfo = GsonUtil.fromJson(tokenValue, HospitalLoginInfo.class);
        if(loginInfo!=null){
            hospitalAdminLogService.addLog(HospitalAdminLog.builder()
                    .username(loginInfo.getUsername())
                    .nickname(loginInfo.getNickname())
                    .remark(annotation.remark())
                    .msg(annotation.value().getMsg())
                    .build());
        }
    }

    private RedisService redisService;

    private HospitalAdminLogService hospitalAdminLogService;

    @Autowired
    public void setRedisService(RedisService redisService) {
        this.redisService = redisService;
    }

    @Autowired
    public void setHospitalAdminLogService(HospitalAdminLogService hospitalAdminLogService) {
        this.hospitalAdminLogService = hospitalAdminLogService;
    }
}
